const { DataTypes } = require('sequelize');
const { sequelize } = require('../utils/database');
const bcrypt = require('bcryptjs');

const User = sequelize.define('User', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  username: {
    type: DataTypes.STRING(50),
    allowNull: false,
    unique: true,
    validate: {
      len: [3, 50],
      notEmpty: true
    }
  },
  email: {
    type: DataTypes.STRING(100),
    allowNull: false,
    unique: true,
    validate: {
      isEmail: true,
      notEmpty: true
    }
  },
  password_hash: {
    type: DataTypes.STRING(255),
    allowNull: false
  },
  avatar_url: {
    type: DataTypes.STRING(500),
    allowNull: true
  },
  bio: {
    type: DataTypes.TEXT,
    allowNull: true
  },
  wallet_address: {
    type: DataTypes.STRING(255),
    allowNull: true,
    unique: true
  },
  is_active: {
    type: DataTypes.BOOLEAN,
    defaultValue: true
  },
  last_login: {
    type: DataTypes.DATE,
    allowNull: true
  },
  role: {
    type: DataTypes.ENUM('user', 'moderator', 'admin', 'superadmin'),
    allowNull: false,
    defaultValue: 'user'
  },
  permissions: {
    type: DataTypes.JSON,
    allowNull: true,
    defaultValue: {}
  },
  created_by: {
    type: DataTypes.INTEGER,
    allowNull: true,
    references: {
      model: 'users',
      key: 'id'
    }
  },
  updated_by: {
    type: DataTypes.INTEGER,
    allowNull: true,
    references: {
      model: 'users',
      key: 'id'
    }
  }
}, {
  tableName: 'users',
  hooks: {
    beforeCreate: async (user) => {
      if (user.password_hash) {
        user.password_hash = await bcrypt.hash(user.password_hash, 12);
      }
    },
    beforeUpdate: async (user) => {
      if (user.changed('password_hash')) {
        user.password_hash = await bcrypt.hash(user.password_hash, 12);
      }
    }
  }
});

// 实例方法：验证密码
User.prototype.validatePassword = async function(password) {
  return await bcrypt.compare(password, this.password_hash);
};

// 实例方法：获取公开信息
User.prototype.getPublicInfo = function() {
  const { password_hash, ...publicInfo } = this.toJSON();
  return publicInfo;
};

// 实例方法：检查是否拥有指定角色
User.prototype.hasRole = function(roles) {
  if (typeof roles === 'string') {
    roles = [roles];
  }
  return roles.includes(this.role);
};

// 实例方法：检查是否为管理员
User.prototype.isAdmin = function() {
  return this.role === 'admin' || this.role === 'superadmin';
};

// 实例方法：检查是否为版主
User.prototype.isModerator = function() {
  return this.role === 'moderator' || this.isAdmin();
};

// 实例方法：检查是否拥有特定权限
User.prototype.hasPermission = function(permission) {
  // 超级管理员拥有所有权限
  if (this.role === 'superadmin') {
    return true;
  }
  
  // 管理员拥有特定权限
  if (this.role === 'admin') {
    const adminExcludedPermissions = ['system.superadmin'];
    if (!adminExcludedPermissions.includes(permission)) {
      return true;
    }
  }
  
  // 版主拥有特定权限
  if (this.role === 'moderator') {
    const moderatorPermissions = [
      'content.review',
      'content.edit',
      'content.delete',
      'user.view',
      'badge.view'
    ];
    if (moderatorPermissions.includes(permission)) {
      return true;
    }
  }
  
  // 检查用户自定义权限
  if (this.permissions && typeof this.permissions === 'object') {
    return !!this.permissions[permission];
  }
  
  return false;
};

module.exports = User; 